/**
*┌──────────────────────────────────────────────────────────────┐
*│　描    述：服务                                                   
*│　作    者：sys                                              
*│　创建时间：2020-12-02 14:55:26   
*│　说    明：代码生成器生成   
*└──────────────────────────────────────────────────────────────┘
*/
using SXFramWork.Core;
using SXFramWork.Model;
using SXFramWork.Repository;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SXFramWork.Service
{
    /// <summary>
	/// SysRolePermission服务层
	/// </summary>
    public class SysRolePermissionService: ISysRolePermissionService
    {
        private readonly ISysRolePermissionRepository _repository;
        private readonly ISysPermissionRepository _perRepository;

        public SysRolePermissionService(ISysRolePermissionRepository repository,ISysPermissionRepository sysPermissionRepository)
        {
            _perRepository = sysPermissionRepository;
            _repository = repository;
        }

        [Transaction]
        public async Task<IApiResult> Add(List<string> list, string roleId)
        {
            //删除出当前角色所有的权限
            await _repository.DeleteAsync(roleId, "sysrolepermission", "roleid");
            List<SysRolePermissionEntity> list_add = new List<SysRolePermissionEntity>();
            foreach(var item in list)
            {
                var data = new SysRolePermissionEntity();
                data.RoleId = roleId;
                data.PermissionId = item;
                list_add.Add(data);
            }
            //批量插入
            var res= await _repository.InsertAsync(list_add);
            return ApiResult.Ok();
        }

        public async Task<IApiResult> GetPermissionList()
        {
            var permissions = await _perRepository.GetAllAsync();
               
            var apis = permissions
                .Where(a => a.Type ==1)
                .Select(a => new { a.Id, a.ParentId, a.Name,a.Platform });

         
            var Allmenus = await _perRepository.GetAllMenus();

            var menus=Allmenus                       
                .Select(a => new
                {
                    a.Id,
                    a.ParentId,
                    Label= a.Name,
                    Apis = apis.Where(b => b.ParentId == a.Id).Select(b => new { b.Id, b.Name }),
                });
            var appApis = apis.Where(c => c.Platform == 1).Select(c => new { c.Id,Label=c.Name });
            return ApiResult.Ok(new {menus=menus,appapis=appApis });
        }

        public async Task<IApiResult> QueryPermission(string roleId)
        {
            var list_permission = await _repository.GetPermissionByRoleId(roleId);

            return ApiResult.Ok(list_permission);
           
        }
    }
}